/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2021-02-24 17:49:09
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-02-25 17:23:02
 * @Description: file content
 */
"use strict";
// const { Service } = require('egg');
import { Service } from "egg";

/**
 *通用基础restful风格的api使用的服务类。
 *
 * @export
 * @class RestfulService
 * @extends {Service}
 */
export default class RestfulService extends Service {
  /**
   *post 插入一条数据
   *
   * @param {orm.defineModel<{}>} Model
   * @param {object} postData
   * @return {*}
   * @memberof RestfulService
   */
  async create(Model, postData) {
    return await Model.create(postData, { raw: true });
  }

  /**
   *获取一条数据
   *
   * @param {orm.defineModel<{}>} Model 模型对象
   * @param {(number | string)} id 主键id
   * @return {*}返回原始一行数据对象。
   * @memberof RestfulService
   */
  async show(Model, id) {
    return await Model.findByPk(id, { raw: true });
  }

  /**
   *修改一条数据
   *
   * @param {*} id 主键id
   * @param {*} updateData 要修改的新数据
   * @param {orm.defineModel<{}>} Model 模型对象
   * @param {(number | string)} [primaryKey] 可选，主键名称。
   * @return {[number,number]} 受影响的行数
   * @memberof RestfulService
   */
  async update(id, updateData, Model, primaryKey) {
    // return await Model.
    // console.log(Model);
    // console.log(Model.tableName);
    // console.log(Model.primaryKeyAttributes);
    // console.log(Model.primaryKeyAttribute);
    // console.log(Model.rawAttributes);
    let k = "";
    if (primaryKey) {
      k = primaryKey;
    } else {
      k = Model.primaryKeyAttribute;
    }

    return await Model.update(updateData, {
      where: {
        [k]: id,
      },
    });
  }

  /**
   *删除一条数据
   *
   * @param {*} id 主键id
   * @param {orm.defineModel<{}>} Model 模型对象
   * @param {(number | string)} [primaryKey] 可选的传入主键名称
   * @return {number} 受影响的行数
   * @memberof RestfulService
   */
  async delete(id, Model, primaryKey) {
    let k = "";
    if (primaryKey) {
      k = primaryKey;
    } else {
      k = Model.primaryKeyAttribute;
    }
    return await Model.destroy({
      where: {
        [k]: id,
      },
    });
  }

  /**
   *批量删除service
   *
   * @param {any[]} idList
   * @param {*} Model
   * @param {*} primaryKey
   * @return {*} 
   * @memberof RestfulService
   */
  async batchDelete(idList:any[],Model,primaryKey){
    let k = "";
    if (primaryKey) {
      k = primaryKey;
    } else {
      k = Model.primaryKeyAttribute;
    }
    return await Model.destroy({
      where: {
        [k]: Array.isArray(idList) ? idList : [idList],
      },
    });
  }

}
